$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/discover/list',
        datatype: "json",
        colModel: [
            {
                label: '文章id',
                name: 'articleId',
                index: "activeId",
                width: 45,
                key: true,
                sortable: false,
                align: 'center'
            },
            {label: '标题', name: 'title', width: 75, sortable: false, align: 'center'},
            {label: '作者', name: 'author', width: 60, sortable: false, align: 'center'},
            {
                label: '内容', name: 'content', width: 45, sortable: false, formatter: function (value, options, row) {
                    return value == null ? "-" : '<a  onclick ="openContent(' + JSON.stringify(row).replace(/"/g, '&quot;')+ ')"> 内容预览 </a>';
                }, align: 'center'
            },
            {label: '跳转地址', name: 'jumpUrl', width: 75, sortable: false, align: 'center'},
            {
                label: '类型', name: 'type', width: 60, sortable: false, align: 'center', formatter: function (value) {
                    return value == 1 ? "单图排版" : "三图排版"
                }
            },
            {label: '创建时间', name: 'createTime', width: 60, sortable: false, align: 'center'},
            {label: '顺序', name: 'sort', width: 75, sortable: false, align: 'center'},
            {label: '写作时间', name: 'writeDate', width: 75, sortable: false, align: 'center'},
            {
                label: '状态', name: 'state', width: 75, sortable: false, formatter: function (value, options, row) {
                    return value == 1 ? "显示" : "隐藏";
                }, align: 'center'
            }

        ],
        viewrecords: true,
        height: "auto",
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        multiboxonly: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },

        gridComplete: function () {

            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            $('#jqGrid').closest("div.ui-jqgrid-view")
                .children("div.ui-jqgrid-titlebar")
                .css("text-align", "center")
                .children("span.ui-jqgrid-title")
                .css("float", "none");
        }
    });
    initalCoverList();
});

var ue = UE.getEditor('editor');

var vm = new Vue({
    el: '#rrapp',
    data: {
        q: {
            state: 0,
            type: 0
        },
        showList: true,
        showImgList: false,
        showUpdate: false,
        showAdd: false,
        title: null,
        states: [
            {
                value: 0,
                msg: '显示/隐藏'
            },
            {
                value: 1,
                msg: '显示'
            },
            {
                value: 2,
                msg: '隐藏'
            }
        ],
        types: [
            {
                value: 0,
                msg: '排版方式'
            },
            {
                value: 1,
                msg: '单图排版'
            },
            {
                value: 2,
                msg: '多图排版'
            }
        ],
        article: {
            articleId: null,
            title: null,
            type: 0,
            author: null,
            content: null,
            state: 0,
            writeDate: null,
            authorHead: null
        },
        discoverId: 0
    },
    methods: {
        query: function () {
            vm.reload();
        },
        clean: function () {
            vm.showList = true;
            vm.showImgList = false;
            vm.showUpdate = false;
            vm.showAdd = false;
            vm.q = {
                state: 0,
                type: 0
            };
            $("#jqGrid").jqGrid('setGridParam', {page: 1});
            vm.reload();
        },

        reload: function () {
            vm.showList = true;
            vm.showImgList = false;
            vm.showUpdate = false;
            vm.showAdd = false;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'state': vm.q.state, 'type': vm.q.type},
                page: page
            }).trigger("reloadGrid");

        },
        showCover: function () {
            let rowid = getSelectedRow();
            if (rowid == null) {
                return;
            }
            let row = $("#jqGrid").jqGrid('getRowData', rowid);
            if (row == null) {
                return;
            }
            console.log(row)
            vm.refresh(row.articleId);
        },
        refresh: function (id) {
            vm.showList = false;
            vm.showImgList = true;
            vm.showUpdate = false;
            vm.showAdd = false;
            $("#imgGrid").jqGrid('setGridParam', {
                url: baseURL + "sys/discover/imgList",
                datatype: "json",
                postData: {'id': id},
                page: 1
            }).trigger("reloadGrid");
        }, update: function () {

            let rowId = getSelectedRow();
            if (rowId == null) {
                return;
            }
            let row = $("#jqGrid").jqGrid('getRowData', rowId);
            if (row == null) {
                return;
            }
            vm.showList = false;
            vm.showImgList = false;
            vm.showUpdate = true;
            vm.showAdd = false;
            $.get(baseURL + "sys/discover/getArticleById/" + row.articleId, r => {
                vm.article = r.article;
                ue.setContent(vm.article.content)
                $("#writeDate").val(r.article.writeDate);
            })

        },
        add: function () {
            vm.showList = false;
            vm.showImgList = false;
            vm.showUpdate = true;
            vm.showAdd = true;
            vm.article = {
                articleId: null,
                title: null,
                type: 0,
                author: null,
                content: null,
                state:0,
                writeDate: null,
                authorHead: null
            }
            $("input[type='file']").val("");

            $("#writeDate").val(new Date().Format("yyyy-MM-dd"));

            ue.setContent("");
            vm.discoverId = 0;
        },modify: function () {
            if (vm.article.articleId == null) {
                vm.uploadHead();
            } else {
                vm.commitUpdate();
            }
        },
        commitUpdate: function () {
            vm.article.content=ue.getContent();
            $.ajax({
                url: baseURL + "sys/discover/updateById",
                contentType: "application/json",
                data: JSON.stringify(vm.article),
                type: "post",
                success: function (r) {
                    if (r.code == 0) {
                        vm.reload();
                    } else {
                        layer.msg(r.msg)
                    }
                }
            })
        }, uploadCovers: function () {
            let files = document.getElementById("cover").files;

            let formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append('files', $("#cover")[0].files[i]);
            }
            formData.append("discoverId", vm.discoverId);

            $.ajax({
                url: baseURL + "sys/discover/addCover",
                type: "POST",
                processData: false,
                contentType: false,
                data: formData,
                success: function (d) {
                    layer.msg(d.msg)
                    vm.reload();
                }
            });


        }, commitAdd: function () {
            if (vm.article.title == null || vm.article.title.length == 0) {
                layer.msg("请填写标题")
                return;
            }
            if (vm.article.author == null || vm.article.author.length == 0) {
                layer.msg("请填写作者")
                return;
            }
            if (vm.article.type == null || vm.article.type == 0) {
                layer.msg("请选择类型")
                return;
            }
            if (vm.article.state == null || vm.article.type == 0) {
                layer.msg("请选择状态")
                return;
            }
            let files = document.getElementById("cover").files;
            if (vm.article.type == 1) {
                if (files.length != 1) {
                    layer.msg("请选择一张图片")
                    return;
                }
            }
            if (vm.article.type == 2) {
                if (files.length != 3) {
                    layer.msg("请选择三张图片")
                    return;
                }
            }
            if (vm.article.writeDate == null) {
                vm.article.writeDate = $("#writeDate").val();
            }

            let content = ue.getContent();
            vm.article.content = content;
            $.ajax({
                url: baseURL + "sys/discover/add",
                contentType: "application/json",
                data: JSON.stringify(vm.article),
                type: "post",
                success: function (r) {
                    if (r.code == 0) {
                        vm.discoverId = r.discoverId;
                        vm.uploadCovers();
                    } else {
                        layer.msg(r.msg)
                    }
                }
            })
        },
        uploadHead() {
            let file = document.getElementById("head");
            if (file == null || file.length == 0) {
                layer.msg("请选择头像")
                return;
            }
            let formData = new FormData();

            formData.append('file', $("#head")[0].files[0]);
            console.log(formData)
            $.ajax({
                url: baseURL + "sys/discover/uploadHead",
                type: "POST",
                processData: false,
                contentType: false,
                data: formData,
                success: function (d) {
                    vm.article.authorHead=d.url;
                    vm.commitAdd();
                }
            });
        },
        deleteArticle:function(){
            let rowid = getSelectedRow();
            if (rowid == null) {
                return;
            }
            let row = $("#jqGrid").jqGrid('getRowData', rowid);
            if (row == null) {
                return;
            }
            $.get(baseURL+"sys/discover/deleteArticleById/" + row.articleId,r=>{
                layer.msg(r.msg)
                vm.reload();
            })
        }
    }
});
Date.prototype.Format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

function openContent(row) {
    $("#content").html(row.content);
    layer.open({
        type: 1,
        title: "内容预览",
        content: $("#content"),
        btn: ['确定'],
        area: ['392px', '716px'],
        btn1: function (index) {
            $("#content").html("");
            layer.close(index);
        }

    })

}

function initalCoverList() {

    $("#imgGrid").jqGrid({
        datatype: "local",
        colModel: [
            {label: 'id', name: 'coverId', width: 100, sortable: false, align: 'center'},
            {label: '图片路径', name: 'imgUrl', width: 200, sortable: false, align: 'center'},
            {
                label: '图片预览', name: 'imgUrl', width: 200, sortable: false, align: 'center',
                formatter: function (value) {
                    return value == null ? '-' : '<a  onclick = "openImg(\'' + value + '\')"> 查看图片 </a>';
                }
            },
            {label: '顺序', name: 'sort', width: 200, sortable: false, align: 'center'},
            {
                label: '操作', name: 'coverId', width: 200, sortable: false, align: 'center', formatter: function (value) {
                    return value == null ? '-' : '<a class="btn btn-success" onclick = "updateImg(\'' + value + '\')"> 修改图片 </a>';
                }
            },
        ],
        viewrecords: true,
        height: "auto",
        rowNum: 10,
        autowidth: true,
        rowList: [10, 30, 50],
        rownumbers: false,
        caption: "图片列表",
        rownumWidth: 25,
        autowidth: true,
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },

        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#imgGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            //隐藏分页条件
            $("#imgGridPager").hide();
            $('#imgGrid').closest("div.ui-jqgrid-view").children("div.ui-jqgrid-titlebar")
                .css("text-align", "center")
                .children("span.ui-jqgrid-title")
                .css("float", "none");

        }
    });
}

//打开图片
function openImg(src) {

    $("#goodsImg").attr("src", src);

    layer.open({
        type: 1,
        title: "请选择",
        content: $("#goodsImg"),
        btn: ['确定'],
        area: ['720px', '640px'],
        btn1: function (index) {
            layer.close(index);
        }

    })
}

function updateImg(id) {
    layer.open({
        type: 1,
        title: "请选择",
        content: $("#imgForm"),
        btn: ['提交', '关闭'],
        area: ['400px', '200px'],
        btn1: function () {
            console.log(id)
            if (!uploadImg(id)) {
                return;
            }
        },
        btn2: function (index) {
            layer.close(index);
        }

    })

}

function uploadImg(id) {
    if ($($("#imgForm input")[0]).val() == null) {
        layer.msg("请选择图片")
        return false;
    }
    var formData = new FormData($("#imgForm form")[0]);
    formData.append("file", $("#imgForm input")[0]);
    $.ajax({
        url: baseURL + "sys/discover/uploadDiscoverCover",
        datatype: 'json',
        type: 'post',
        data: formData,
        cache: false,
        traditional: true,
        contentType: false,
        processData: false,
        success: function (msg) {
            if (msg.url != null && msg.url != '') {
                modifyImg(msg.url, id);
                $($("#imgForm input")[0]).val("");
            }
        }

    })
}

function modifyImg(url, id) {
    $.get(baseURL + "sys/discover/updateCover", {'url': url, 'id': id}, r => {
        if (r.code == 0) {
            layer.msg("上传成功")
            vm.refresh(id);
            layer.closeAll();
        } else {
            layer.msg("上传失败")
        }
    })

}